package com.training.hatton.dropboxclient.processor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.ResultReceiver;

import com.training.hatton.base.RequestDataWrapper;
import com.training.hatton.dropboxclient.ContextHolder;
import com.training.hatton.dropboxclient.content.Metadata;
import com.training.hatton.dropboxclient.http.HttpManager;
import com.training.hatton.dropboxclient.processor.common.DropboxListModelProcessor;
import com.training.hatton.dropboxclient.service.ServiceHelper;

public class DownloadFileProcessor extends DropboxListModelProcessor<Metadata> {

	public DownloadFileProcessor(RequestDataWrapper dataWrapper, ResultReceiver resultReceiver) {
		super(dataWrapper, resultReceiver);
	}

	private static final String HEADER_METADATA_NAME = "x-dropbox-metadata";

	@Override
	public void executeProcess(HttpRequestBase request) throws Exception {
		sign(request);
		HttpResponse responce = HttpManager.get(ContextHolder.getInstance().getContext()).executeAndResponce(request);
		InputStream source = responce.getEntity().getContent();
		String fileData = responce.getFirstHeader(HEADER_METADATA_NAME).getValue();
		writeFile(source, fileData);
		Bundle resultData = new Bundle();
		resultData.putBundle(ServiceHelper.EXTRA_DATA_REQUEST, getRequestData().getData());
		sendData(SUCCESS_CODE, resultData);
	}

	private void writeFile(InputStream source, String fileData)
			throws Exception {
		FileOutputStream fos = null;
		try {
			Metadata data = new Metadata(fileData);
			File filesDir = ContextHolder.getInstance().getContext().getFilesDir();
			File parent = new File(filesDir.getAbsolutePath(), data.getParent());
			parent.mkdirs();
			File file = new File(parent, data.getName());
			fos = new FileOutputStream(file);
			int bufferSize = 2048;
			byte[] buffer = new byte[bufferSize];
			while (source.read(buffer) != 0) {
				fos.write(buffer);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (source != null) {
				try {
					source.close();
				} catch (Exception e) {
					throw e;
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					throw e;
				}
			}
		}

	}

	@Override
	public Metadata createModel(JSONObject jsonObject) {
		return new Metadata(jsonObject);
	}

	@Override
	public HttpRequestBase buildHttpRequest(String url) {
		HttpGet request = new HttpGet(url);
		return request;
	}
}
